﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using vHCS.HR.Business;
using vHCS.HR.Entities;
using vHCS.SYS.Business;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using System.Data;
using Core.Common.Session;

using K2CoreLib;
using vHCS.K2App.Shared;

#region K2 process

#endregion

namespace vHCS.K2App.MdlK2
{
    public partial class TerminationRequestHis : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region CONST

        protected const string _CMD_LAWDATE = "LawDate";

        #endregion
        # region Global
        private string EmpId = string.Empty;
        private long contractType = 0;
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // Check user incharge to view history
                string userAccess = SessionManager.UserDomain;
                int Id = Convert.ToInt32(Request.QueryString["ID"].ToString());
                HistoryComment his = new HistoryComment();
                if (!his.CheckUserInCharge(userAccess, Id, 2)) // If user not incharge
                {
                    Response.Redirect("../UnAuthorize.htm");
                }

                string User = Request.QueryString["User"] == null ? "" : Request.QueryString["User"].ToString();
                string ID = Request.QueryString["ID"] == null ? "" : Request.QueryString["ID"].ToString();

                TER_AppForResignationCollection collection = new TER_AppForResignationCollection();
                TER_AppForResignationDTO dto = new TER_AppForResignationDTO();

                this.EmpHeaderInFo.LoadEmpInfo(User);
                DataTable dat = new DataTable();

                dat = collection.LoadEmpInfo(User);

                EmpId = dat.Rows[0]["EmployeeId"].ToString().Trim();

                TER_DecideLeaveWorkCollection clDWL = new TER_DecideLeaveWorkCollection();
                TER_DecideLeaveWorkDTO dtoDLW = new TER_DecideLeaveWorkDTO();
                dtoDLW = clDWL.SelectEmpID(Convert.ToInt64(EmpId));
                if (dtoDLW != null)
                {
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("10187");
                    ex.AdditionInfo = new String[] { dtoDLW.EmpCode };
                    throw ex;
                }
                else
                {
                    dto = collection.SelectByID(Convert.ToInt64(ID)).DTO;
                    contractType = this.LoadEmpInfo(EmpId);
                    if (!IsPostBack)
                    {
                        if (dto != null)
                        {
                            LoadEmpForUpdate(dto);
                        }
                        else
                        {
                            this.txtRequestDate.SelectedDate = DateTime.Now;
                            this.txtLasDateForLaw.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                            this.txtLastDateMyDream.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                        }
                    }
                }

                //Kiem tra user dang nhap de hien thong tin HRBP duyet
                K2Collection col_k2 = new K2Collection();
                bool checkuser = col_k2.CheckCurrentUser(Convert.ToInt64(ID), SessionManager.UserDomain);
                if (checkuser)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "ShowRework", "ShowRework();", true);
                    //Gan
                    string link = collection.GetSurveyLink(Convert.ToInt64(EmpId));
                    string[] arr_link = link.Split(';');

                    //Gán link survey do nhân viên làm
                    if (string.IsNullOrEmpty(arr_link[0]))
                    {
                        hplSurvey_Emp.Text = "[Exit survey chưa được thực hiện]";
                    }
                    else
                    {
                        hplSurvey_Emp.NavigateUrl = arr_link[0];
                        hplSurvey_Emp.Text = arr_link[0];
                    }

                    //Gán link survey do hrbp làm
                    if (string.IsNullOrEmpty(arr_link[1]))
                    {
                        hplSurver_HRBP.Text = "[Exit survey chưa được thực hiện]";
                    }
                    else
                    {
                        hplSurver_HRBP.NavigateUrl = arr_link[1];
                        hplSurver_HRBP.Text = arr_link[1];
                    }

                    //pnlType.Enabled = false;
                    EnableCommentHRBP(false);
                    pnlType.Visible = true;
                    pnlExitSurvey.Visible = true;
                    //pnlExcutor.Enabled = false;

                    //SetComboValue(cboExcutor, excutor, true);
                    //Load thông tin HRBP nhập vào
                    TER_AppForResignationCollection clApp = new TER_AppForResignationCollection();
                    //Load thông tin lấy bên đơn xin thôi việc (Loại thôi việc, lý do thôi việc, blacklist)
                    long terminaltype = 0;
                    long terminalreason = 0;
                    bool blacklist = false;
                    string reason = "";
                    Int16 propose;
                    string str_proposenote = "";
                    clApp.GetTermination(Convert.ToInt64(EmpId), out terminaltype, out terminalreason, out blacklist, out reason, out propose, out str_proposenote);
                    SetComboValue(cboTerminalType, terminaltype, true);

                    dtsTerminalReason.SelectParameters["terminationtypeid"].DefaultValue = terminaltype.ToString();
                    cboTerminalReason.DataSourceID = dtsTerminalReason.ID;
                    cboTerminalReason.DataBind();
                    SetComboValue(cboTerminalReason, terminalreason, true);
                    if (propose == 1) radAccept.Checked = true;
                    else radRefuse.Checked = true;
                    txtReasonComment.Text = str_proposenote;
                    if (blacklist)
                        radNo.Checked = true;
                    else
                        radYes.Checked = true;
                    //
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }

        }
        /// <summary>
        /// load thông tin nhân viên xin thôi việc 
        /// </summary>
        /// <param name="dto"></param>thông tin TER_AppForResignationDTO
        protected void LoadEmpForUpdate(TER_AppForResignationDTO dto)
        {
            if (dto.RequireDate.Year > 1)
            {
                this.txtRequestDate.SelectedDate = dto.RequireDate;
            }
            else
            {
                this.txtRequestDate.SelectedDate = null;
            }
            this.txtLastDateMyDream.SelectedDate = dto.AspirateDate;
            this.txtLasDateForLaw.SelectedDate = dto.LawDate;
            if (dto.ApproveDate.Year > 1)
            {
                this.txtLastDateApprove.SelectedDate = dto.ApproveDate;
            }
            else
            {
                this.txtLastDateApprove.SelectedDate = null;
            }
            this.txtTerminalReason.Text = dto.LeaveWorkReason.Trim();
        }
        /// <summary>
        /// Laod thông tin người cho thôi việc
        /// </summary>
        /// <param name="EmpId"></param>id của nhân viên
        /// <returns></returns>
        protected long LoadEmpInfo(string EmpId)
        {
            try
            {
                TER_DecideLeaveWorkCollection collection = new TER_DecideLeaveWorkCollection();
                HR_EmpHeaderInfoDTO dto = new HR_EmpHeaderInfoDTO();
                dto = collection.LoadEmpInfo(Convert.ToInt64(EmpId));
                if (dto != null)
                {
                    this.txtRequester.Text = dto.FullName;
                    this.txtOrgChart.Text = dto.OrgChart;
                    this.txtLocation.Text = dto.WorkingOffice;
                    this.txtStartDate.Text = dto.JoinDate.ToShortDateString();
                    this.txtEmpCode.Text = dto.EmpCode;
                    this.txtSignDate.Text = dto.EffectiveDate.ToShortDateString();
                    this.txtJobTitle.Text = dto.JobTitle;

                    this.txtContractType.Text = dto.ContractName;

                    return dto.LSContractTypeID;
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return -1;
        }

        public void EnableCommentHRBP(bool enable)
        {
            try
            {
                cboTerminalType.Enabled = enable;
                cboTerminalReason.Enabled = enable;
                radAccept.Enabled = enable;
                radRefuse.Enabled = enable;
                txtReasonComment.ReadOnly = !enable;
                radYes.Enabled = enable;
                radNo.Enabled = enable;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
    }
}